const query=require('../db/mysql');
const {success,error}=require('../model/model');
const {md5}=require('utility');

const jwt =require('jsonwebtoken');
class ListController{
    register=async (ctx)=>{
        const {username,password,nickname}=ctx.request.body;
        const isHaveSql=`select * from users where username="${username}"`;
        const isHave=await query(isHaveSql);
        if(isHave.length){
            ctx.body=error('账号已存在');
            return;
        } 
        const sql = `insert into users(username,password,nickname) values("${username}","${md5(String(password))}","${nickname}")`
        const data=await query(sql);
        if(data.affectedRows===1){
            ctx.body===success('注册成功')
        }else{
            ctx.body=error('注册失败')
        }
    }
    login=async(ctx)=>{
        const {username,password}=ctx.request.body;
        const sql=`select id,username,nickname from users where username="${username}" and password="${md5(String(password))}"`;
        const data=await query;
        if(data.length){
            ctx.body=success({
                data:data[0],
                token:jwt.sign({id:data[0].id,username:data[0].username},"data2")
            })
        }else{
            ctx.body=error('请查询账号密码')
        }
    }
}
module.exports =new ListController()

